package com.test.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnLineCountListener implements HttpSessionListener,
		ServletContextListener, ServletContextAttributeListener
{
	private int count;
	
	@Override
	public void attributeAdded(ServletContextAttributeEvent arg0)
	{
		log("attributeAdded('" + arg0.getName() + "', '" + arg0.getValue() + "')");
	}

	@Override
	public void attributeRemoved(ServletContextAttributeEvent arg0)
	{
		log("attributeRemoved('" + arg0.getName() + ", '" + arg0.getValue() + "')");
	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent arg0)
	{
		log("attributeReplaced('" + arg0.getName() + ", '" + arg0.getValue() + "')");
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0)
	{
		log("contextDestroyed");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0)
	{
		log("contextInitialized");
	}

	@Override
	public void sessionCreated(HttpSessionEvent arg0)
	{
		count++;
		setContext(arg0);
		System.out.println("count");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0)
	{
		count--;
		setContext(arg0);
	}

	private void setContext(HttpSessionEvent se)
	{
		se.getSession().getServletContext().setAttribute("onLine", new Integer(count));
	}
	
	private void log(String msg)
	{
		System.out.println("ContextListener: " + msg);
	}
}
